package com.gome.ocean.server.velocity;

import java.io.StringWriter;
import java.util.Map;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.log.CommonsLogLogChute;

/**
 * 模板生成引擎
 * @author haqiaolong
 *
 */
public enum VelocityEngineManager {
	
	INSTANCE;

	private VelocityEngine velocityEngine;

	private VelocityContext toolContext;

	private VelocityEngineManager() {
		velocityEngine = new VelocityEngine();
		velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "class");
		velocityEngine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_CACHE, "true"); // 缓存
		velocityEngine.setProperty(RuntimeConstants.INPUT_ENCODING, "utf-8");
		velocityEngine.setProperty(RuntimeConstants.OUTPUT_ENCODING, "utf-8");
		velocityEngine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM, new CommonsLogLogChute()); // 统一日志
		toolContext = new VelocityContext();
		toolContext.put("stringUtils", new org.apache.commons.lang.StringUtils());
		velocityEngine.init();
	}

	public String merge(String templateContent, Map<String, Object> context) {
		StringWriter out = new StringWriter();
		VelocityContext vContext = new VelocityContext(toolContext);
		for (Map.Entry<String, Object> entry : context.entrySet()) {
			vContext.put(entry.getKey(), entry.getValue());
		}
		velocityEngine.evaluate(vContext, out, "dynamic template", templateContent);
		return out.toString();
	}
}
